package com.itheima.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.wxpay.sdk.WXPay;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.config.MyConfig;
import com.itheima.dto.OrdersDto;
import com.itheima.mapper.*;
import com.itheima.pojo.*;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrdersService;
import com.itheima.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class OrdersServiceimpl implements OrdersService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;


    @Override
    public R submit(Orders orders) {
        // 获得当前登陆的用户名
        Long userId = BaseContext.threadLocal.get();
        // 根据用户名查出购物车信息
        LambdaQueryWrapper<ShoppingCart> cartWrapper = new LambdaQueryWrapper<>();
        cartWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(cartWrapper);
        //  找出当前用户
        User user = userMapper.selectById(userId);
        // 查出地址信息
        AddressBook addressBook = addressBookMapper.selectById(orders.getAddressBookId());
        // 补全订单信息
        orders.setStatus(1);   // 订单状态
        orders.setUserId(userId);
        orders.setAddress(addressBook.getDetail());  // 收货地址
        orders.setAmount(sumCartMoney(shoppingCarts));  //  计算金额
        orders.setConsignee(addressBook.getConsignee());  // 收货人姓名
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setOrderTime(LocalDateTime.now());  // 下单时间
        orders.setPayMethod(1);
        orders.setNumber(UUID.randomUUID().toString());   // 订单号
        orders.setPhone(addressBook.getPhone());
        orders.setUserName(user.getName());    // 登陆的用户姓名
        ordersMapper.insert(orders);
        //  组装订单明细 批量保存订单明细
        // 1. 将购物车集合转换成明细集合
        String s = JSON.toJSONString(shoppingCarts);
        List<OrderDetail> orderDetails = JSON.parseArray(s, OrderDetail.class);
        // 2.封装orderId到明细中
        orderDetails.stream().forEach(c -> c.setOrderId(orders.getId()));
        ArrayList<String> names = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetails) {
            names.add(orderDetail.getName());
        }
        orderDetailService.saveBatch(orderDetails);    //  批量添加
        shoppingCartService.clean();   // 清空购物用户的购物车


        //todo 请求微信获得支付的二维码信息
        MyConfig mc = new MyConfig();
        WXPay wxPay = null; ///wxPay 核心支付类
        try {
            wxPay = new WXPay(mc);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, String> map = new HashMap();
        //封装请求参数
        map.put("body","红烧肉套餐");//商品描述
        map.put("out_trade_no",orders.getId()+"");//商品描述 唯一
        map.put("total_fee","1");//商品描述  1分钱  模拟一分钱
        map.put("spbill_create_ip","127.0.0.1");//服务器地址
        //用户支付成功后，微信会调用这个地址来告诉商家是否支付成功
        //1.微信 此地址必须外网能够访问
        map.put("notify_url","http://32633x11x9.zicp.vip/wx/notify");//服务器地址
        map.put("trade_type","NATIVE ");//支付方式
        //发送请求
        try {//二维码连接
            Map<String, String> reponseMap = wxPay.unifiedOrder(map);
            reponseMap.put("out_trade_no",orders.getId()+""); //自己添加一个订单的信息
            return R.success(reponseMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error("下单失败");

    }

    @Override
    public R userPage(Integer page, Integer pageSize) {
        Long userId = BaseContext.threadLocal.get();
        IPage<Orders> p = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Orders::getOrderTime);
        IPage<Orders> ordersIPage = ordersMapper.selectPage(p, wrapper);

        List<Orders> orders = ordersIPage.getRecords();
        String s = JSON.toJSONString(orders);
        List<OrdersDto> ordersDtos = JSON.parseArray(s, OrdersDto.class);

        for (OrdersDto ordersDto : ordersDtos) {
            LambdaQueryWrapper<OrderDetail> wrapper3 = new LambdaQueryWrapper<>();
            wrapper3.eq(OrderDetail::getOrderId, ordersDto.getId());
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(wrapper3);
            ordersDto.setOrderDetails(orderDetails);
        }

        String jsonString = JSON.toJSONString(ordersIPage);
        Page page1 = JSON.parseObject(jsonString, Page.class);
        page1.setRecords(ordersDtos);
        return R.success(page1);
    }

    @Override
    public Orders getById(String out_trade_no) {
        Orders orders = ordersMapper.selectById(Long.parseLong(out_trade_no));
        return orders;
    }

    @Override
    public void updateStatus(String out_trade_no, String transaction_id) {
        //1.根据订单id 查询出订单对象
        Orders orders = ordersMapper.selectById(out_trade_no);
        //2.修改订单状态并且存储流水号
        orders.setStatus(2);
        orders.setNumber(transaction_id); //存储流水号
        //3.保存到数据库
        ordersMapper.updateById(orders);
    }

    private BigDecimal sumCartMoney(List<ShoppingCart> shoppingCarts) {
        BigDecimal bigDecimal = new BigDecimal(0);
        for (ShoppingCart shoppingCart : shoppingCarts) {
            bigDecimal.add(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())));
        }
        return bigDecimal;
    }

}
